<template>
  <div class="schedule-list">
    <FullCalendar
      ref="fullCalendar"
      :options="calendarOptions"
    >
      <template #eventContent="{ event }">

        <el-tooltip
          placement="bottom"
          effect="light"
          popper-class="custom-tooltip"
        >
          <div class="schedule-list__event" @click="handleTest(event)">
            <div class="title line-clamp-1">{{ event.title }}</div>
          </div>
          <template #content>
            <div class="event-popover">
              <div class="event-popover__title">
                {{ event?.title }}
              </div>

              <div class="event-popover__info">
                <i class="el-icon-time" />
                <span>{{ getTimeTitle(event?.start, event?.end) }}</span>
              </div>
              <div class="event-popover__info">
                <i class="el-icon-user" />
                <span>{{ event.extendedProps?.userName }}</span>
              </div>
              <div
                class="flex event-popover__info"
                style="justify-content: flex-end"
              >
                <el-button
                  type="primary"
                  size="mini"
                  @click="handleViewDetail(event.id)"
                >
                  查看详情
                </el-button>
              </div>
            </div>
          </template>
        </el-tooltip>

      </template>
    </FullCalendar>
  </div>
</template>
<script>
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlulgin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import resourceTimelinePlugin from '@fullcalendar/resource-timeline'
import dayjs from 'dayjs'

export default {
  name: 'ScheduleList',
  components: {
    FullCalendar
  },
  props: {
    scheduleList: {
      type: Array,
      default: () => []
    },

    date: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      calendarOptions: {
        contentHeight: 'auto',
        initialView: 'resourceTimeline',
        plugins: [interactionPlugin, resourceTimelinePlugin],
        schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
        allDaySlot: false,
        initialDate: new Date(),
        axisFormat: 'h(:mm)tt',
        locale: 'zh-cn',
        // resourceAreaHeaderContent: '会议室名称',
        headerToolbar: null,
        resourceAreaWidth: '15%',
        resourceAreaColumns: [
          {
            field: 'date',
            headerContent: '日期',
            headerClassNames: 'resource-area-columns'
          },
          {
            field: 'room',
            headerContent: '会议室名称',
            headerClassNames: 'resource-area-columns',
            cellContent: function(arg) {
              const extendedProps = arg.resource.extendedProps
              return {
                html: `
                 <span class="room-btn pointer" data-room-id="${arg.resource.id}">
                  ${extendedProps.room}
                 </span>`
              }
            }
          }
        ],
        resources: [],
        slotLabelFormat: { // 时间格式配置
          hour: 'numeric',
          minute: '2-digit', // 分钟显示2位
          omitZeroMinute: false, // 是否显示分钟
          meridiem: 'short'
        },
        views: {
          resourceTimeline: {
            height: '100%',
            width: '120px'
          }
        },
        // 最小时间
        slotMinTime: '08:00:00',
        // 最大时间
        slotMaxTime: '18:00:00',
        handleWindowResize: true,
        weekNumberCalculation: 'ISO',
        datesSet: () => {
          this.bindCustomCellEvents()
        },
        resourcesSet: () => {
          this.bindCustomCellEvents()
        }
      }
    }
  },
  computed: {
    getResourceDate() {
      return this.date ? dayjs(this.date).format('MM-DD') : dayjs().format('MM-DD')
    }
  },
  watch: {
    scheduleList: {
      handler(newVal) {
        this.scheduleListFormat()
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.bindCustomCellEvents()
  },
  methods: {
    handleTest(info) {
      console.log('info --------->', info)
    },
    scheduleListFormat() {
      const resources = []
      const events = []
      this.scheduleList.forEach(item => {
        console.log('item --------->', item)
        resources.push({
          id: item.id,
          date: this.getResourceDate,
          room: item.name,
          quantity: item.quantity,
          notes: item.notes
        })

        item?.conference_room_reservation.forEach(room => {
          events.push({
            id: room.id,
            title: room.reason,
            userName: room.user.username,
            start: room.start_time,
            end: room.end_time,
            resourceId: item.id
          })
        })
      })
      console.log('events --------->', events)

      this.$set(this.calendarOptions, 'events', events)
      this.$set(this.calendarOptions, 'resources', resources)
      if (this.date) {
        this.$refs?.fullCalendar?.getApi().gotoDate(this.date)
      } else {
        this.$refs?.fullCalendar?.getApi().gotoDate(new Date())
      }

      // this.bindCustomCellEvents()
    },

    getTimeTitle(start, end) {
      const startDate = dayjs(start)
      const endDate = dayjs(end)

      // 日期部分：MM月DD日（周X）
      const dateStr = `${startDate.format('MM月DD日')}（${'周日_周一_周二_周三_周四_周五_周六'.split('_')[startDate.day()]}）`

      // 时间部分：HH:mm~HH:mm
      const timeStr = `${startDate.format('HH:mm')}~${endDate.format('HH:mm')}`

      // 拼接结果
      return `${dateStr} ${timeStr}`
    },

    bindCustomCellEvents() {
      const cells = document.querySelectorAll('.room-btn')
      cells.forEach(cell => {
        cell.addEventListener('click', (e) => {
          const resourceId = e.currentTarget.getAttribute('data-room-id')
          const resource = this?.$refs?.fullCalendar?.getApi().getResourceById(resourceId)

          if (resource) {
            const extendedProps = resource.extendedProps
            this.showRoomDetailDialog(extendedProps)
            // 在这里执行你的业务逻辑，比如打开弹窗、跳转等
          }
        })
      })
    },

    showRoomDetailDialog(roomInfo) {
      console.log('roomInfo --------->', roomInfo)
    },
    handleViewDetail(id) {
      this.$emit('viewDetail', id)
    }
  }
}
</script>
<style lang="scss" scoped>
.schedule-list {
  &__event {
    padding: 12px 16px;
    background-color: #D9ECFF;
    border-radius: 4px;
    border-left: 4px solid #1890FF;
    color: #303133;
    font-size: 14px;
  }

  ::v-deep(.fc-h-event) {
    background-color: transparent;
    border: none;
  }

  ::v-deep(.fc-datagrid-cell-frame) {
    display: flex;
    align-items: center;
  }

  ::v-deep(.resource-area-columns) {
    .fc-datagrid-cell-main {
      color: #909399 !important;
      font-size: 14px !important;
      font-weight: 700 !important;
    }
  }

  ::v-deep(.fc-datagrid-cell-main) {
    color: #606266;
    font-size: 14px;
  }

  ::v-deep(.fc-timeline-slot-frame) {
    font-weight: 700;
    font-size: 16px;
    color: #9E9E9E;
  }

  ::v-deep(.el-icon-view) {
    font-size: 14px;
    color: #1890FF;
  }

  ::v-deep(.fc-timeline-event-harness) {
    top: 50% !important;
    transform: translateY(-50%);
  }

}

.event-popover {
  &__title {
    color: #303133;
    font-size: 14px;
    font-weight: 700;
  }

  &__info {
    color: #606266;
    margin-top: 8px;
    font-size: 12px;
    > i {
      margin-right: 5px;
    }
  }
}

.pointer {
  cursor: pointer;
}

</style>
